<script lang="ts">
  export default {
    name: 'Cartegory',
  };
</script>

<script setup lang="ts">
  import { computed, onMounted, ref, onUnmounted, watchEffect } from 'vue';
  import { showConfirmDialog, showToast, showLoadingToast, closeToast } from 'vant';
  import { useRouter, useRoute } from 'vue-router'
  import API_HOME from '@/apis/home';
  import { useI18n } from 'vue-i18n';
  const route = useRoute();
  const router = useRouter();
  const { t } = useI18n()
  // 商品列表数据
  const list = ref([]);
  // 分页参数
  const params = ref({
    limit: 6,
    page: 1,
    category_id: '',
    keyword: ''
  });

  // 加载状态
  const loading = ref(false);
  // 是否正在加载更多
  const loadingMore = ref(false);
  // 是否还有更多数据
  const hasMore = ref(true);

  // 页面加载时获取初始数据
  onMounted(() => {
    // 添加滚动事件监听
    window.addEventListener('scroll', handleScroll);

  });

  // 组件卸载时移除事件监听
  onUnmounted(() => {
    window.removeEventListener('scroll', handleScroll);
  });

  // 获取分类列表
  const getCategoryList = async () => {
    if (loading.value) return;
    loading.value = true;
    try {
      const res = await API_HOME.goodsList(params.value);
      if (res.code == 1) {
        // 如果是第一页，直接赋值
        if (params.value.page === 1) {
          list.value = res.data.data;
        } else {
          // 追加数据
          list.value = [...list.value, ...res.data.data];
        }
        // 检查是否还有更多数据
        hasMore.value = res.data.data.length >= params.value.limit;
      }
    } catch (error) {
      showToast('Failed to load products');
      console.error(error);
    } finally {
      loading.value = false;
      loadingMore.value = false;
    }
  };

  // 滚动处理函数
  const handleScroll = () => {
    // 避免重复加载或没有更多数据时触发
    if (loading.value || loadingMore.value || !hasMore.value) return;
    // 计算滚动位置
    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    const windowHeight = window.innerHeight;
    const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;

    // 距离底部300px时触发加载
    if (scrollTop + windowHeight >= scrollHeight - 300) {
      loadMore();
    }
  };

  // 加载更多数据
  const loadMore = () => {
    if (!hasMore.value) return;
    loadingMore.value = true;
    params.value.page++;
    getCategoryList();
  };

  // 刷新列表
  const refreshList = () => {
    params.value.page = 1;
    getCategoryList();
  };

  let categoryName = ref('')
  // 获取分类名称
  const getCategoryName = async () => {
    let res = await API_HOME.goodsCategory()
    if (res.code == 1) {
      let item = res.data.find((e) => {
        return e.id == route.query.id;
      })
      if (item) {
        categoryName.value = item.name
      }
    }
  };
  watchEffect(() => {
    const newId = route.query.id;
    const newKeyword = route.query.keyword;

    // 只有参数确实变化时才更新和请求
    if (newId !== params.value.category_id || newKeyword !== params.value.keyword) {
      params.value.category_id = newId;
      params.value.keyword = newKeyword;
      list.value = []
      params.value.page = 1
      if (newId) {
        getCategoryName()
      }
      getCategoryList();
    }
  });
</script>

<template>
  <div>
    <Shop_headers></Shop_headers>
    <div class="shopContainer">
      <div class="category">{{params.keyword?params.keyword:categoryName }}</div>

      <!-- 商品列表 -->
      <Goods_list :filteredProducts="list" v-if="list.length > 0"></Goods_list>

      <!-- 空状态 -->
      <div class="none" v-else>
        <div class="category">{{t('home.NoResults')}} "{{ params.keyword?params.keyword:categoryName }}"</div>
        <div class="tip">
          {{t('home.emptyTips')}}
        </div>
        <van-button type="primary" round class="refresh-btn" @click="refreshList">
          {{t('home.TryAgain')}}
        </van-button>
      </div>

      <!-- 加载更多状态 -->
      <div class="loading-more" v-show="loadingMore">
        <van-loading type="spinner" size="24px">Loading...</van-loading>
      </div>

      <!-- 没有更多数据提示 -->
      <div class="no-more" v-show="!hasMore && list.length > 0">
        {{t('home.Nomore')}}
      </div>
    </div>
    <Shop_footer></Shop_footer>
  </div>
</template>

<style lang="less" scoped>
  .category {
    margin: 26px 0;
    font-size: 32px;
    font-weight: 600;
    color: #333;
    text-align: center;
  }

  .none {
    text-align: center;
    padding: 10% 0;

    .category {
      font-size: 24px;
      margin-bottom: 20px;
    }

    .tip {
      font-size: 16px;
      color: #666;
      line-height: 1.6;
      max-width: 500px;
      margin: 0 auto 30px;
    }

    .refresh-btn {
      width: 180px;
      height: 44px;
      font-weight: 500;
    }
  }

  .loading-more {
    text-align: center;
    padding: 20px 0;
    color: #999;
    font-size: 14px;

    .van-loading {
      display: inline-flex;
      align-items: center;
      gap: 10px;
    }
  }

  .no-more {
    text-align: center;
    padding: 20px 0;
    color: #999;
    font-size: 14px;
    border-top: 1px solid #eee;
  }

  /* 适配移动端和PC */
  @media (max-width: 768px) {
    .category {
      font-size: 24px;
      margin: 15px 0;
    }

    .none {
      padding: 20% 20px;

      .category {
        font-size: 20px;
      }

      .tip {
        font-size: 14px;
      }
    }
  }
</style>